#include "StdAfx.h"
#include "NetHander.h"
#include "NetManage.h"
CNetSevice::CNetSevice(const ZMString& address, const ZMString& port) : m_io_service(),
m_acceptor(m_io_service),
m_isServerRun(false)
{
	boost::asio::ip::tcp::resolver resolver(m_io_service);
	boost::asio::ip::tcp::resolver::query query(address, port);
	boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query);
	m_acceptor.open(endpoint.protocol());
	m_acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
	m_acceptor.bind(endpoint);
	m_acceptor.listen();

	m_pNewConnect.reset(new CNetConnect(m_io_service));
	m_acceptor.async_accept(m_pNewConnect->Socket(),
		boost::bind(&CNetSevice::handle_accept, this,
			boost::asio::placeholders::error));
}


void CNetSevice::handle_accept(const boost::system::error_code& e)
{
	if (!e)
	{
		CNetConnectManage::GetInstance()->Start(m_pNewConnect);
		m_pNewConnect.reset(new CNetConnect(m_io_service));
		m_acceptor.async_accept(m_pNewConnect->Socket(),
			boost::bind(&CNetSevice::handle_accept, this,
				boost::asio::placeholders::error));
	}
}

void CNetSevice::Stop()
{
	// The server is stopped by cancelling all outstanding asynchronous
	// operations. Once all operations have finished the io_service::run() call
	// will exit.
	m_acceptor.close();
	CNetConnectManage::GetInstance()->Stop_All();
	m_io_service.reset();
	m_isServerRun = false;
}

void CNetSevice::Start()
{
	boost::thread t(boost::bind(&CNetSevice::StartMain, this));
}

void CNetSevice::StartMain()
{
	if (!m_isServerRun)
	{
		m_isServerRun = true;
		m_io_service.reset();
		m_io_service.run();
		m_isServerRun = false;

	}
}
